<template>
  <!-- :row-selection="rowSelection" -->
  <ProTable
    ref="tableRef"
    :fetchListApi="fetchDepartment"
    :format-response="formatResponse"
    :columns="columns"
    hidePagination
    row-key="deptId"
  >
    <template #expandIcon="{ expanded, onExpand, record }">
      <DownOutlined
        v-if="record.children"
        :rotate="expanded ? 0 : -90"
        :style="{ float: 'left' }"
        @Click="
          (e) => {
            onExpand(record, e);
          }
        "
      />
    </template>
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="() => onAdd()" code="system:dept:add"
          >新增</b-button
        >
      </Space>
    </template>
    <template #operation="{ record }">
      <b-button icon="detail" type="link" @click="() => onView(record)"
        >详情</b-button
      >
      <b-button
        icon="add"
        type="link"
        @click="() => onAdd(record.deptId)"
        code="system:dept:add"
        >新增</b-button
      >
      <b-button
        v-if="record.parentId !== 0"
        icon="del"
        type="link"
        @click="() => onDelete(record.deptId)"
        code="system:dept:remove"
        >删除</b-button
      >
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
  <AssignOperator ref="assignOperatorRef" />
</template>

<script setup lang="tsx">
import { computed, ref, useTemplateRef } from 'vue';
import { DownOutlined } from '@ant-design/icons-vue';
import { Modal, Space, Tag } from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { handleTree, listToEnum, listToOption } from '@/utils/utils';
import {
  createDepartment,
  deleteDepartment,
  fetchDepartment,
  fetchSysNormalDisable,
  updateDepartment,
} from '@/api/system';
import { hasPermission } from '../../../permission';
import AssignOperator from './components/AssignOperator.vue';

const tableRef = ref();

const sysNormalDisableOptions = ref<Global.Option[]>([]);
const sysNormalDisableEnum = ref<Record<string, any>>([]);

const departments = ref([]);
const formatResponse = (res: any) => {
  const rows = handleTree(res.data, 'deptId', 'parentId');
  departments.value = rows as any;
  return {
    rows,
    total: rows.length,
  };
};

const init = () => {
  fetchSysNormalDisable().then((res) => {
    sysNormalDisableOptions.value = listToOption(
      res.data,
      'dictLabel',
      'dictValue',
    ) as Global.Option[];
    sysNormalDisableEnum.value = listToEnum(res.data, 'dictValue', 'dictLabel');
  });
};

init();

const selectKeys = ref<number[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectKeys.value,
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '部门名称',
    dataIndex: 'deptName',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '排序',
    dataIndex: 'orderNum',
    hideInSearch: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueEnum: {
      ...sysNormalDisableEnum.value,
    },
    customRender({ text }) {
      return (
        <Tag color={text === '0' ? 'success' : 'error'}>
          {sysNormalDisableEnum.value[text]}
        </Tag>
      );
    },
  },

  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 260,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '上级部门',
    type: 'treeSelect',
    field: 'parentId',
    rules: [{ required: true, message: '请选择上级部门', trigger: 'blur' }],
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
    colProps: {
      span: 24,
    },
    props: {
      placeholder: '请选择',
      treeData: departments.value,
      fieldNames: {
        label: 'deptName',
        value: 'deptId',
      },
    },
  },
  {
    label: '部门名称',
    type: 'input',
    field: 'deptName',
    rules: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
    props: {
      placeholder: '请输入部门名称',
    },
  },
  {
    label: '显示排序',
    type: 'number',
    field: 'orderNum',
    rules: [{ required: true, message: '请输入显示排序', trigger: 'blur' }],
    props: {
      placeholder: '请输入显示排序',
      min: 0,
    },
  },
  {
    label: '负责人',
    type: 'input',
    field: 'leader',
    props: {
      placeholder: '请输入负责人',
    },
  },
  {
    label: '联系电话',
    type: 'input',
    field: 'phone',
    props: {
      placeholder: '请输入联系电话',
    },
  },
  {
    label: '邮箱',
    type: 'input',
    field: 'email',
    props: {
      placeholder: '请输入邮箱',
    },
  },
  {
    label: '状态',
    type: 'radio',
    field: 'status',
    props: {
      options: sysNormalDisableOptions.value,
    },
  },
]);

const { FormModal, open } = useFormModal({
  size: 'small',
  column: 2,
  formProps: { labelCol: { span: 6 } },
});

const onAdd = async (id?: string) => {
  open({
    title: '新增',
    defaultValue: {
      status: '0',
      parentId: id,
    },
    serviceApi: async (params: any): Promise<any> => {
      await createDepartment(params);
      sleep(() => tableRef.value.refresh());
    },
  });
};

const onView = async (record: any) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: {
      ...record,
    },
    hasEditPermission: hasPermission('system:dept:edit'),
    serviceApi: async (params: any): Promise<any> => {
      await updateDepartment({
        ...params,
      });
      sleep(() => tableRef.value.refresh());
    },
  });
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async (id: number) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选项？`,
    onOk: async () => {
      await deleteDepartment([id]);
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
    },
  });
};

const assignOperatorRef = useTemplateRef('assignOperatorRef');
const onLinkOperationUser = (deptId: number) => {
  assignOperatorRef.value?.open?.(deptId);
};
</script>
